package com.fish.anne.webapp.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GridJsonUtil {
	public String data2Jsonstring(int totalRecord,String page,int totalPage,String[] tableHead,String[][] tableBody){
		String mystring="";
		JSONObject json=new JSONObject();
		JSONArray array = new JSONArray();
		JSONObject cell=null;
		try {
			json.put("records", totalRecord+"");
			json.put("page", page);
			json.put("total", totalPage+"");
			//Collection c = new ArrayList();
			//c.add("id:111");
			//c.add("name:222");
			if(tableBody!=null){
				for(int i=0;i<tableBody.length;i++){
					cell = new JSONObject();
					for(int j=0;j<tableHead.length;j++){
						cell.put(tableHead[j], tableBody[i][j]);
					}
					array.put(cell);
				}
				
				
				json.put("rows", array);
			}
			//json.put("rows", c);
			mystring = json.toString();
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mystring;
	}
	
	public String data2Jsonstring2(int totalRecord,String page,int totalPage,String[] tableHead,String[][] tableBody,String param){
		String mystring="";
		JSONObject json=new JSONObject();
		JSONArray array = new JSONArray();
		JSONObject cell=null;
		JSONArray array2 = new JSONArray();
		JSONObject cell2=null;
		try {
			json.put("records", totalRecord+"");
			json.put("page", page);
			json.put("total", totalPage+"");
			//Collection c = new ArrayList();
			//c.add("id:111");
			//c.add("name:222");
			if(tableBody!=null){
				for(int i=0;i<tableBody.length;i++){
					cell = new JSONObject();
					for(int j=0;j<tableHead.length;j++){
						cell.put(tableHead[j], tableBody[i][j]);
					}
					array.put(cell);
				}
				json.put("rows", array);
			}
			cell2 = new JSONObject();
			cell2.put("param", param);
			array2.put(cell2);
			json.put("userdata", cell2);
			
			//json.put("rows", c);
			mystring = json.toString();
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mystring;
	}
	
	
	public boolean stringToPage(HttpServletResponse response,String mystring){
		try{
			response.setCharacterEncoding("utf8");
			PrintWriter pw = response.getWriter();
			//pw.write(json); // 将JSON数据返回页面
			pw.write(mystring);
			pw.flush();
			pw.close();
			
		}catch(Exception e){
			return false;
		}
		return true;
		
	}
}
